package com.example.api.service.impl;

import com.example.api.constant.StatusConst;
import com.example.api.dto.FoodDTO;
import com.example.api.mapper.FoodMapper;
import com.example.api.pojo.Food;
import com.example.api.query.FoodQuery;
import com.example.api.service.FoodService;
import com.example.api.utils.PageResult;
import com.example.api.vo.FoodVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class FoodServiceImpl implements FoodService {

    @Resource
    FoodMapper foodMapper;

    @Override
    public PageResult<FoodVO> find(FoodQuery foodQuery) {
        //设置是否需要分页
        PageHelper.startPage(foodQuery.getPage(),foodQuery.getPageSize());  //告诉PageHelper此处需要分页

        //List
        Page<FoodVO> page = (Page<FoodVO>) foodMapper.find(foodQuery);

        PageInfo<FoodVO> pageInfo = page.toPageInfo();


        List<FoodVO> foodVOList = pageInfo.getList();
        long total = pageInfo.getTotal();

        PageResult<FoodVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setList(foodVOList);

        return pageResult;
    }

    @Override
    public void add(FoodDTO foodDTO) {
        Food food = new Food();
        BeanUtils.copyProperties(foodDTO,food);

        food.setCreateTime(new Date());
        food.setUpdateTime(new Date());

        food.setStatus(StatusConst.ACTIVE_STATUS);

        foodMapper.add(food);
    }

    @Override
    public FoodVO findById(long id) {
        return foodMapper.findById(id);
    }

    @Override
    public void update(long id, FoodDTO foodDTO) {
        Food food = new Food();
        BeanUtils.copyProperties(foodDTO,food);

        food.setId(id);
        food.setUpdateTime(new Date());
        foodMapper.update(food);
    }

//    @Override
//    public void deleteById(long id) {
//        foodMapper.deleteById(id);
//    }

    @Override
    public void updateStatus(long id, Byte status) {
        Food food = new Food();
        food.setId(id);
        food.setUpdateTime(new Date());
        food.setStatus(status);
        foodMapper.update(food);
    }

    @Override
    public int findCountByCategoryId(long categoryId) {
        return foodMapper.findCountByCategoryId(categoryId);
    }

}

